
import React from "react";
import request from "@/utils/request";
import { useState, useCallback, useEffect } from "react";
import {
  Table,
  Button,
  Popconfirm,
  message,
  Input,
  Space,
  InputNumber,
  Form,
  Typography,
  Modal,
  Select,
} from "antd";

import { auto } from "async";
function Suguan() {
  const { Search } = Input;
  const [datalist, setDatalist] = useState([]);
  const [isModalVisible, setIsModalVisible] = useState(false);

  // 数据列表
  const getData = useCallback(async function () {
    const { data } = await request.get("/users/all");
    setDatalist(data.ret.data);

  }, []);
  useEffect(() => {
    getData();
  }, []);
  // 查询功能
  const onSearch = useCallback(async function (value) {
    const { data } = await request.post("/users/select", {
      id: value * 1,
    });
    if (data.code === 200 && data.ret.length !== 0) {
      setDatalist(data.ret);
    } else {
      getData();
    }
  }, []);

  // 添加功能
  const showModal = () => {
    setIsModalVisible(true);
  };

  const handleCancel = () => {
    setIsModalVisible(false);
  };
  const AddItem = () => {
    const { Option } = Select;

    const onFinish = useCallback(async function (values) {
      console.log(values);
      const { data } = await request.post("/users/add", {
        id: values.id,
        username: values.username,
        password: values.password,
        sex: values.sex,
        age: values.age,
        scope: values.scope,
        address: values.address,
      });
      if (data.code === 200) {

        getData();
        message.success("添加成功");
      } else {
        message.warning("添加失败");
      }
      console.log(data);
      console.log("Success:", values);
    }, []);

    const onFinishFailed = (errorInfo) => {
      console.log("Failed:", errorInfo);
    };

    const validateMessages = {
      number: {
        range: "${label} 必须在 ${min} 与 ${max}之间",
      },
    };

    return (
      <Form
        name="basic"
        labelCol={{
          span: 8,
        }}
        wrapperCol={{
          span: 16,
        }}
        initialValues={{
          remember: true,
        }}
        onFinish={onFinish}
        onFinishFailed={onFinishFailed}
        autoComplete="off"
        validateMessages={validateMessages}
      >
        <Form.Item
          label="姓名"
          name="username"
          rules={[
            {
              required: true,
              message: "请输入姓名！",
            },
          ]}
        >
          <Input style={{ width: 150 }} />
        </Form.Item>

        <Form.Item
          name="sex"
          label="性别"
          rules={[
            {
              required: true,
              message: "请选择性别!",
            },
          ]}
        >
          <Select allowClear style={{ width: 100 }}>
            <Option value="男">男</Option>
            <Option value="女">女</Option>
          </Select>
        </Form.Item>

        <Form.Item
          label="密码"
          name="password"
          rules={[
            {
              required: true,
              message: "请输入密码！",
            },
          ]}
        >
          <Input style={{ width: 170 }} />
        </Form.Item>

        <Form.Item
          label="工号"
          name="id"
          rules={[
            {
              required: true,
              message: "请输入工号！",
            },
            {
              type: "number",
            },
          ]}
        >
          <InputNumber style={{ width: 170 }} />
        </Form.Item>

        <Form.Item
          label="年龄"
          name="age"
          rules={[
            {
              type: "number",
              min: 0,
              max: 99,
            },
            {
              required: true,
              message: "请输入年龄！",
            },
          ]}
        >
          <InputNumber />
        </Form.Item>

        <Form.Item
          label="管理范围"
          name="scope"
          rules={[
            {
              required: true,
              message: "请输入管理范围！",
            },
          ]}
        >
          <Input style={{ width: 210 }} />
        </Form.Item>

        <Form.Item
          label="住址"
          name="address"
          rules={[
            {
              required: true,
              message: "请输入住址！",
            },
          ]}
        >
          <Input style={{ width: 230 }} />
        </Form.Item>

        <Form.Item
          wrapperCol={{
            offset: 10,
            span: 16,
          }}
        >
          <Button type="primary" htmlType="submit">
            提交
          </Button>
        </Form.Item>
      </Form>
    );
  };
  // 可编辑表格（修改）
  let list = datalist.map((value) => {
    value["key"] = value._id;
    return value;
  });

  const EditableCell = ({
    editing,
    dataIndex,
    title,
    inputType,
    record,
    index,
    children,
    ...restProps
  }) => {
    const inputNode = inputType === "number" ? <InputNumber /> : <Input />;
    return (
      <td {...restProps}>
        {editing ? (
          <Form.Item
            name={dataIndex}
            style={{
              margin: 0,
            }}
            rules={[
              {
                required: true,
                message: `Please Input ${title}!`,
              },
            ]}
          >
            {inputNode}
          </Form.Item>
        ) : (
          children
        )}
      </td>
    );
  };

  const EditableTable = () => {
    const [form] = Form.useForm();
    const [data, setData] = useState(list);
    const [ids, setIds] = useState([]);
    const [editingKey, setEditingKey] = useState("");
    const [bottom] = useState('bottomCenter')


    const isEditing = (record) => record.key === editingKey;

    const edit = (record) => {
      form.setFieldsValue({
        id: "",
        username: "",
        password: "",
        age: "",
        scope: "",
        address: "",
        ...record,
      });
      setEditingKey(record.key);
    };

    const cancel = () => {
      setEditingKey("");
    };

    const save = async (key) => {
      try {
        const row = await form.validateFields();
        const newData = [...data];
        const index = newData.findIndex((item) => key === item.key);
        if (index > -1) {
          const item = newData[index];
          newData.splice(index, 1, { ...item, ...row });
          setData(newData);
          const curItem = newData[index];
          const mes = await request.put("/users/update", {
            id: curItem.id,
            username: curItem.username,
            password: curItem.password,
            sex: curItem.sex,
            age: curItem.age,
            scope: curItem.scope,
            address: curItem.address,
          });
          if (mes.data.code === 200) {
            message.success("修改成功");
          } else {
            message.warning("修改失败");
          }
          // console.log(mes);
          setEditingKey("");
        } else {
          newData.push(row);
          setData(newData);
          setEditingKey("");
        }
      } catch (errInfo) {
        console.log("Validate Failed:", errInfo);
      }
    };

    const handleDelete = async (key) => {
      const newData = [...data];
      // console.log(ids);
      const list = newData.filter((item) => {
        return item.id !== key;
      });
      const id = ids;
      id.push(key);
      setIds(id);
      const mes = await request.delete("/users/delete", { data: { ids } });
      if (mes.data.code === 200) {
        message.success("删除成功");
      } else {
        message.warning("删除失败");
      }
      console.log("mes", mes);
      setData(list);
      console.log("oData", list);
    };

    const columns = [
      {
        // 设置表头
        title: "工号",
        // 设置当前列显示什么数据
        dataIndex: "id",
        width: "15%",
        render: (text) => {
          return <h4>{text}</h4>;
        },
        editable: true,
      },
      {
        title: "姓名",
        dataIndex: "username",
        width: "12%",
        render: (text) => {
          return <h4>{text}</h4>;
        },
        editable: true,
      },
      {
        title: "性别",
        dataIndex: "sex",
        width: "8%",
        render: (text) => {
          return <h4>{text}</h4>;
        },
        editable: true,
      },
      {
        title: "年龄",
        dataIndex: "age",
        width: "10%",
        render: (text) => {
          return <h4>{text}</h4>;
        },
        editable: true,
      },
      {
        title: "密码",
        dataIndex: "password",
        width: "15%",
        render: (text) => {
          return <h4>{text}</h4>;
        },
        editable: true,
      },
      {
        title: "管理范围",
        dataIndex: "scope",
        width: "12%",
        render: (text) => {
          return <h4>{text}</h4>;
        },
        editable: true,
      },
      {
        title: "住址",
        dataIndex: "address",
        Tooltip: true,
        width: "15%",
        render: (text) => {
          return <h4>{text}</h4>;
        },
        editable: true,
      },
      {
        title: "操作",
        dataIndex: "operation",
        width: "20%",
        render: (_, record) => {
          const editable = isEditing(record);
          return editable ? (
            <span>
              <a
                href="javascript:;"
                onClick={() => save(record.key)}
                style={{
                  marginRight: 8,
                }}
              >
                保存
              </a>
              <Popconfirm
                title="确定取消吗"
                onConfirm={cancel}
                okText="确定"
                cancelText="取消"
              >
                <a>取消</a>
              </Popconfirm>
            </span>
          ) : data.length >= 1 ? (
            <div>
              <Typography.Link
                disabled={editingKey !== ""}
                onClick={() => edit(record)}
              >
                编辑
              </Typography.Link>
              <Popconfirm
                title="Sure to delete?"
                onConfirm={() => {
                  handleDelete(record.id);
                }}
              >
                <Button type="danger" size="small" style={{ marginLeft: 10 }}>
                  删除
                </Button>
              </Popconfirm>
            </div>
          ) : (
            <Typography.Link
              disabled={editingKey !== ""}
              onClick={() => edit(record)}
            >
              编辑
            </Typography.Link>
          );
        },
      },
    ];
    const mergedColumns = columns.map((col) => {
      if (!col.editable) {
        return col;
      }

      return {
        ...col,
        onCell: (record) => ({
          record,
          inputType: col.dataIndex === "age" ? "number" : "text",
          dataIndex: col.dataIndex,
          title: col.title,
          editing: isEditing(record),
        }),
      };
    });

    return (
      <>
        <Form form={form} component={false}>
          <Table
            id="roleTable"
            components={{
              body: {
                cell: EditableCell,
              },
            }}
            bordered
            dataSource={data}
            columns={mergedColumns}
            rowClassName="editable-row"
            pagination={{ pageSize: 10, position: [bottom] }}
            scroll={{ y: 440 }} 
          />
        </Form>
      </>
    );
  };

  return (
    <div>
      <Space direction="vertical" style={{ marginBottom: "20px" }}>
        <Search
          placeholder="请输入工号"
          allowClear
          enterButton="查询"
          size="large"
          onSearch={onSearch}
        />
      </Space>
      <Button
        type="primary"
        size="middle"
        style={{ float: "right", marginTop: "20px" }}
        onClick={showModal}
      >
        添加
      </Button>
      <Modal
        title="添加宿管"
        visible={isModalVisible}
        onCancel={handleCancel}
        style={{ margin: auto, height: "600px" }}
        footer={null}
      >
        <AddItem />
      </Modal>
      <EditableTable />
    </div>
  );
}

export default Suguan;
